#!/usr/bin/env python

import sys
import argparse
from collections import defaultdict

warn = 'Warning: {0} file "{1}" is touched by more than one package: {2}\n'


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('packages_file_list', nargs='*',
                        help='The packages-file-list to check from')
    parser.add_argument('-t', '--type', metavar="TYPE",
                        help='Report as a TYPE file (TYPE is either target, staging, or host)')

    args = parser.parse_args()

    if not len(args.packages_file_list) == 1:
        sys.stderr.write('No packages-file-list was provided.\n')
        return False

    if args.type is None:
        sys.stderr.write('No type was provided\n')
        return False

    file_to_pkg = defaultdict(list)
    with open(args.packages_file_list[0], 'rb') as pkg_file_list:
        for line in pkg_file_list.readlines():
            pkg, _, file = line.rstrip(b'\n').partition(b',')
            file_to_pkg[file].append(pkg)

    for file in file_to_pkg:
        if len(file_to_pkg[file]) > 1:
            # If possible, try to decode the binary strings with
            # the default user's locale
            try:
                sys.stderr.write(warn.format(args.type, file.decode(),
                                             [p.decode() for p in file_to_pkg[file]]))
            except UnicodeDecodeError:
                # ... but fallback to just dumping them raw if they
                # contain non-representable chars
                sys.stderr.write(warn.format(args.type, file,
                                             file_to_pkg[file]))


if __name__ == "__main__":
    sys.exit(main())
